package cn.bluethink.timescaledb.controller;

import cn.bluethink.timescaledb.entity.Dynamic;
import cn.bluethink.timescaledb.entity.RequestDTO;
import cn.bluethink.timescaledb.entity.ResponseDTO;
import cn.bluethink.timescaledb.service.DynamicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@CrossOrigin
@RequestMapping("/dynamic")
public class DynamicController {

    Logger logger = LoggerFactory.getLogger(DynamicController.class);

    @Autowired
    DynamicService dynamicService;

    /**
     * @param file
     * @param tableName
     * @return
     */
    @PostMapping("/save")
    public String save(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName) {
        String str;
        List<Dynamic> dynamics = new ArrayList<>();
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RequestDTO requestDTO = new RequestDTO();
        String response = "";
        try {
            InputStream fileInputStream = file.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));
            while ((str = br.readLine()) != null) {
                String[] params = str.split(",");
                Dynamic dynamic = new Dynamic();
                //文件每行第一、二分别是number、time
                dynamic.setNumber(Integer.valueOf(params[0]));
                dynamic.setTime(format1.parse(params[1]));

                List<Map<String, String>> locations = new ArrayList<>();
                List<String> list = Arrays.asList(params);
                List<String> paramList = new ArrayList<>(list);
                paramList.subList(0, 2).clear();

                for (int i = 0; i < paramList.size(); i++) {
                    Map<String, String> location = new HashMap<>();
                    StringBuilder locationKey = new StringBuilder("location_");
                    location.put(locationKey.append(i).toString(), paramList.get(i));
                    locations.add(location);
                }

                dynamic.setLocation(locations);
                dynamics.add(dynamic);
            }
            requestDTO.setData(dynamics);
            requestDTO.setTableName(tableName);
            response = dynamicService.insertBatch(requestDTO);
        } catch (FileNotFoundException e) {
            logger.error("保存动态数据异常:" + e.getClass().getName() + "," + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("保存动态数据异常:" + e.getClass().getName() + "," + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            logger.error("保存动态数据异常:" + e.getClass().getName() + "," + e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    /**
     * @param requestDTO
     * @return
     */
    @GetMapping("/query")
    public ResponseDTO query(@RequestBody RequestDTO requestDTO) {
        List<Dynamic> dynamics = dynamicService.queryByTableName(requestDTO.getTableName());
        return dynamics == null ? new ResponseDTO(null, "表名不存在", new Date()) : new ResponseDTO(dynamics, "success", new Date());
    }

}
